package com.yuan.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuan.reggie.common.CustomerException;
import com.yuan.reggie.dto.SetmealDto;
import com.yuan.reggie.mapper.DishMapper;
import com.yuan.reggie.mapper.SetmealMapper;
import com.yuan.reggie.pojo.Dish;
import com.yuan.reggie.pojo.Setmeal;
import com.yuan.reggie.pojo.SetmealDish;
import com.yuan.reggie.service.DishService;
import com.yuan.reggie.service.SetmealDishService;
import com.yuan.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * @author yuanxingke
 * @date 2022/7/30 0:03
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    @Transactional
    public void saveWithDish(SetmealDto dishList) {
        //1、保存菜品相关信息
        this.save(dishList);

        //2、不全菜品信息
        List<SetmealDish> setmealDishes = dishList.getSetmealDishes();
        //3、设置相关菜品的id
        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(dishList.getId()));
        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    @Transactional
    public void removeWithDish(Long[] ids) {
        //先查询状态，如果正在售卖，不能删除
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Setmeal::getId,ids);
        lambdaQueryWrapper.eq(Setmeal::getStatus,1);
        int count = this.count(lambdaQueryWrapper);
        if(count>0){
            throw new CustomerException("套餐正在售卖，无法删除");
        }

        //先删除套餐主表的内容
        this.removeByIds(Arrays.asList(ids));

        //再删除对于的菜品表

        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(setmealDishLambdaQueryWrapper);

    }
    @Override
    public SetmealDto getByIdWithDish(Long id) {
        //根据id查询
        Setmeal setmeal = this.getById(id);

        //查询菜品
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> list = setmealDishService.list(lambdaQueryWrapper);

        SetmealDto setmealDto = new SetmealDto();
        setmealDto.setSetmealDishes(list);

        BeanUtils.copyProperties(setmeal,setmealDto);
        return setmealDto;
    }
}
